//
//  PowerMeterVC.swift
//  LtwooEletrics
//
//  Created by K YTYan on 2024/10/10.
//

import UIKit
import MCToast
import SwiftEntryKit
import SwiftyUserDefaults
import Localize_Swift
import JXSegmentedView
import SwiftUI
import SnapKit
import CoreBluetooth


class PowerMeterVC: DeviceInfoBaseVC   {
  
    private var isSmoothness: Bool = false
    private var isBalance: Bool = false
    let saveButton: UIButton = {
        let view : UIButton = UIButton()
        view.layer.masksToBounds = true
        view.layer.cornerRadius = SUITABLE(22)
        view.setTitle( String.localized_zore_calibration, for: .normal)
        view.titleLabel?.font = .lt_sys_regular(ofSize: SUITABLE(18))
        view.addGradient(CGRect(x: 0, y: 0, w: LT_SCREEN_WIDTH, h: SUITABLE(44)))
        return view
    }()
    
    private var dataSources:[MineModel] = []
    private let tableView: LTTableView = {
        let tableView = LTTableView(style: .grouped)
        return tableView
    }()
     // 记录灵敏值
    private var gpValue: Int = 100
    private var oldLaps: Int = 0
    private var oldTimestamp:Int = 0
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        self.navBar?.isTranslucent = true
        self.view.backgroundColor = .clear
        self.getSensitivity()
    }
 
    override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        // 硬性条件--注册通知中心
 
    }
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
 
    }
    override func viewDidDisappear(_ animated: Bool) {
         super.viewDidDisappear(animated)
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // 硬性条件--注册通知中心
        NotificationCenter.default.addObserver(self, selector: #selector(handlNotificationPM(_:)), name: NSNotification.Name(self.className), object: nil)
        
 
        self.loadDatas()
        
    }
 
    // MARK: - BLEManagerDelegate & BLEManagerOtherDelegate
    /// 后拨 - 在通知中心的回调函数中处理通知
    @objc func handlNotificationPM(_ notification: Notification) {
         
        let io = notification.object as! IOManger
        /// 任何指令返回的 09/11
       self.analysisOthePM(io.characteristic!, io.instruct!)
    }
    
    // 其他指令 -  返回09内容
    private func analysisOthePM(_ c: CBCharacteristic, _ sendInsCode: String = "") {
  
        guard c.value != nil else {
            Dlog("不解析"); return
        }
        let bytes: [UInt8] = [UInt8](c.value!)
        if c.uuid.uuidString == "6E400003-B5A3-F393-E0A9-E50E24DCCA9E" {
            let _insValue = c.value?.toAscii()
            let arys = _insValue?.split(":")
            if arys?.count == 0 { return }
            if let v = _insValue, v.contains("gp") { // 是否包含gp指令
               self.gpValue = 100 + Int(arys![1])!
    
            }
            
            self.dataSources[5].content = "\(self.gpValue)%"
          
            DispatchQueue.main.async {
                let isEnabled = UIView.areAnimationsEnabled
                UIView.setAnimationsEnabled(false)
                let indexPath5 = IndexPath(row: 5, section: 0)
                self.tableView.reloadRows(at: [indexPath5], with: UITableView.RowAnimation.none)
                UIView.setAnimationsEnabled(isEnabled)
            }
            
        }
        if c.uuid.uuidString == "2A63" {
            Dlog("YTYanK：\n------------当前档位>>--->\((bytes)) ->>>>>>>>>>>\(sendInsCode)")
            let endIndex =  bytes.count
            if endIndex > 0 {
                let _power = Int.bytesToInt(Array(bytes[2...3]), length: 2, bigEndian: true)
                let lapsNumber =  Int.bytesToInt(Array(bytes[4...5]), length: 2, bigEndian: false)
                let timestamp = Int.bytesToInt(Array(bytes[6...7]),length: 2, bigEndian: false)
                
                if self.oldTimestamp == 0  && self.oldLaps == 0 {
                    self.oldLaps = lapsNumber
                    self.oldTimestamp = timestamp
                }else {
                    var _timer: Int = timestamp
                    var _laps: Int =  lapsNumber
                    var _timerReset = false
                    var _lapsReset = false
                
                    if _timer < self.oldTimestamp {
                        _timer += 65535
                        _timerReset = true
                    }
              
                    if _laps < self.oldLaps {
                        _laps  +=  65535
                        _lapsReset = true
                    }
                    
                    let _rLaps: Int = _laps - self.oldLaps
                    let _rTimes: Int = _timer - self.oldTimestamp
                    let rpm  =  Double(_rLaps) / Double(_rTimes)
                    let _rpmInt =  Int(rpm * 1024.0 * 60.0)
     
                    if _timerReset  {
                        _timer -= 65535
                        _timerReset = false
                    }
                    if _lapsReset  {
                        _laps -= 65535
                        _lapsReset = false
                    }
                    // 记录
                    self.oldLaps = _laps
                    self.oldTimestamp = _timer
                    
                    self.dataSources[0].content = "\(_power) w"
                    self.dataSources[1].content = "\(_rpmInt) rpm"
                  
                    DispatchQueue.main.async {
                        let isEnabled = UIView.areAnimationsEnabled
                        UIView.setAnimationsEnabled(false)
                        let indexPath0 = IndexPath(row: 0, section: 0)
                        let indexPath1 = IndexPath(row: 1, section: 0)
                        self.tableView.reloadRows(at: [indexPath0,indexPath1], with: UITableView.RowAnimation.none)
                        UIView.setAnimationsEnabled(isEnabled)
                    }
                }

            }
        }
 
   
 
    }
    
    
    private func loadDatas(){
        let titles:[String] = [String.localized_power_meter ,String.localized_cadences,String.localized_left_right_balance, String.localized_pedaling_smoothness,String.localized_chain_fall_calibration, String.localized_power_sensitivity]
        self.structureModel(titles: titles);
    }
 
 
    override func setupUI() {
        
        self.title = .localized_dmvc_0_title
        setupTableView()
        view.addSubview(tableView)
        tableView.backgroundColor = UIColor(hexString: "#1F1F1F", alpha: 1)
        tableView.layer.cornerRadius = 12
        tableView.snp.makeConstraints { (make) in
            make.left.right.equalToSuperview()
            make.top.equalTo(20)
            make.height.equalToSuperview().multipliedBy(0.68)
        }
        
        
 
        view.addSubview(saveButton)
        saveButton.addTarget(self, action: #selector(calibrationAction), for: UIControl.Event.touchUpInside)
        saveButton.snp.makeConstraints { make in
            make.bottom.equalToSuperview()
            make.left.equalToSuperview()
            make.right.equalToSuperview()
            make.height.equalTo( SUITABLE(44))
        }
 
    }
 
 
   // MARK: - 通知
   override func addObserver() {
        NotificationCenter.default.addObserver(self, selector: #selector(loadBluetoothData(notification:)), name: Notification.Name(rawValue: kLoadBluetoothDataNotification), object: nil)
       
       BLEManager.sharedInstance.openNotify(ble: (self.deviceModel?.engine!)!, enabled: true, service:  LTBLEService.COMMUNITY_DATA.service, charac: LTBLEService.COMMUNITY_DATA.Charac.notify)
   }
   @objc func loadBluetoothData(notification: Notification) {
       Dlog("---通知传参------>\(String(describing: notification.object))")
          ///  通知进来就取消该通知
       self.removeNotificationObserver(kLoadBluetoothDataNotification)
 
       
       // 模拟
       DispatchQueue.main.asyncAfter(deadline: .now() + 3) {
           // 加载完成蓝数据
           if self.delegate != nil {
               self.delegate!.loadingCompleted(self)
           }
       }

   }


   deinit {
       Dlog("--------------->释放？？？？DeviceInfo7401VC")
   }
    
    
    private func setupTableView() {
        tableView.delegate = self
        tableView.dataSource = self
        tableView.rowHeight = LTEntryCell.heightForCell()
        tableView.separatorStyle = .none
        tableView.backgroundColor = .black
        LTEntryCell.registerInTableView(tableView: tableView)
    }
    
    /// 根据标题构造 25系列 内容对象
    private func structureModel(titles: [String]) {
        self.dataSources.removeAll()
        var i = 0
        for value in titles {
            let model = MineModel()
            model.title = value
            model.id = i
            model.isHideUnderline = false
 
            if value ==  String.localized_power_sensitivity {
                model.content = "\(self.gpValue)%"
            }else if value == String.localized_power_meter  {
                model.content = "0 w"
            }else if value == String.localized_cadences {
                model.content = "0 rpm"
            }else {
                model.content = ""
            }
 
  
            if  i == titles.count - 1  {
                model.isHideUnderline = true
            }

            dataSources.append(model)
            i += 1
        }

    }
    
    
   @objc private func calibrationAction() {
       Dlog("零点校准Zero point calibration")
       self.showBox(index: 6)
     
    }
}
 

 

 
//MARK: - TableViewDelegate
extension PowerMeterVC: UITableViewDelegate, UITableViewDataSource {
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return dataSources.count
    }
 
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        return nil
    }
    
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return SUITABLE(10)
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return SUITABLE(10)  //CGFloat.leastNormalMagnitude
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        return nil
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        let cell: LTEntryCell =  LTEntryCell(style: .default, reuseIdentifier: LTEntryCell.identifier())
        let item = dataSources[indexPath.row]
        let curTitle = item.title
        Dlog("查询\(indexPath.row)项------------->\(item.content)")
        
        if curTitle == String.localized_left_right_balance {
            cell.reloadView(withModel: item, .titleSwitchCell)
            cell.setSwitchState(open: isBalance)
        }else if  curTitle == String.localized_pedaling_smoothness {
            cell.reloadView(withModel: item, .titleSwitchCell)
            cell.setSwitchState(open: isSmoothness)
        } else if curTitle == String.localized_power_sensitivity {
            cell.reloadView(withModel: item, .titleRLArrowCell)
        }else {
            cell.reloadView(withModel: item, .titleCell)
        }
      
        cell.hiddenLine(dataSources[indexPath.row].isHideUnderline)
        
        return cell
        
    }
    

    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        Dlog("点击了\(indexPath.row)")
        let curTitle = dataSources[indexPath.row].title
 
        if  curTitle == String.localized_left_right_balance {
            self.isBalance = !self.isBalance
            tableView.beginUpdates()
            tableView.reloadRows(at:  [indexPath], with: .automatic)
            tableView.endUpdates()
            
        }else if   curTitle == String.localized_pedaling_smoothness {
            self.isSmoothness = !self.isSmoothness
            tableView.beginUpdates()
            tableView.reloadRows(at:  [indexPath], with: .automatic)
            tableView.endUpdates()
        }else if  curTitle == String.localized_power_sensitivity {
            showGBox(index: indexPath.row)
        }
        else if curTitle == String.localized_chain_fall_calibration || curTitle == String.localized_zore_calibration {
            showBox(index: indexPath.row)
        }
        
       
    }
    private func showGBox(index: Int) {
        let showBox = BoxBullet(type: .upgradeProgressBox(default: self.gpValue))
        showBox.tipValue =  "调节功率灵敏度会影响功率准确性，请酌情谨慎使用。"
        showBox.titleValue =  "功率灵敏度"
        
        showBox.cancelBlock = { _ in }
        showBox.selectedBlock = { value in
            let _newValue = ":\(value)".toAsciiBytes()
            self.setSensitivity(value: _newValue) {
                DispatchQueue.main.async {
                    self.dataSources[5].content = "\(self.gpValue)%"
                    self.tableView.beginUpdates()
                    self.tableView.reloadRows(at:  [IndexPath(row: 5, section: 0)], with: .automatic)
                    self.tableView.endUpdates()
                    MCToast.mc_text(String.localized_vc_set_Success, duration: 2)
                }
            }
        }
        
        showBox.setSensitivityBlock = { type, limitView,  callbackValue in
            var _new = self.gpValue
            var countValue =  -(100 - self.gpValue)
            switch type {
            case .Down:
                if _new > 80 {
                    _new -= 1
                    countValue -= 1
                }else {
                    _new = 80
                    countValue = -20
                }
            default:
                    if  _new < 120 {
                        _new += 1
                        countValue += 1
                    }else {
                        _new = 120
                        countValue = 20
                    }
            }

            self.gpValue = _new
            limitView.updateTickMark(max: 120, min: 80, cur: _new)
            callbackValue(countValue)
        }
        BoxBullet.showStyle(showBox)
    }
    
 
    private func showBox(index: Int) {
        let showBox = BoxBullet(type: .tipBox2)
 
   
        if index ==  6 {
            showBox.tipValue =  String.localized_tip_reset_calibration
            showBox.titleValue = String.localized_zore_calibration
            
        }else if index == 4{
            showBox.tipValue = String.localized_tip_open_calibration
            showBox.titleValue = String.localized_Tip
        }

        showBox.cancelBlock = { _ in }
        showBox.boxBulletBlock = {
            
            self.calibrationCA {
                self.calibrationCG()
                MCToast.mc_text(String.localized_calibration_finish, duration: 2)
            }
        }
 
        BoxBullet.showStyle(showBox)
    
    }
}

//MARK: 指令操作
extension PowerMeterVC {
    
    func calibrationCA( _ completion: (()->Void)? = nil) {
        let ins = LTInstruction()
        ins.content = PW_ca_INS
        BLEManager.sharedInstance.sendValue(with: (self.deviceModel?.engine!)!, instruction: ins) { state in
            completion?()
        }
    }
    
    func calibrationCG(_ completion: (()->Void)? = nil) {
        let ins = LTInstruction()
        ins.content = PW_cg_INS
        BLEManager.sharedInstance.sendValue(with: (self.deviceModel?.engine!)!, instruction: ins) { state in
            completion?()
        }
    }
    func setSensitivity(value: [UInt8], _  completion: (()->Void)? = nil) {
        let ins = LTInstruction()
        ins.content = PW_cp_INS
        ins.data = value
        BLEManager.sharedInstance.sendValue(with: (self.deviceModel?.engine!)!, instruction: ins) { state in
            completion?()
        }
    }
    func getSensitivity(_  completion: (()->Void)? = nil) {
        let ins = LTInstruction()
        ins.content = PW_gp_INS
        BLEManager.sharedInstance.sendValue(with: (self.deviceModel?.engine!)!, instruction: ins) { state in
            completion?()
        }
    }
    
}
